package com.changdu.seatunnel.admin.controller;

import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.changdu.seatunnel.admin.entity.SyncConfig;
import com.changdu.seatunnel.admin.entity.SyncTask;
import com.changdu.seatunnel.admin.handlers.JobStateScanHandler;
import com.changdu.seatunnel.admin.pojo.BatchRequest;
import com.changdu.seatunnel.admin.pojo.JobParams;
import com.changdu.seatunnel.admin.pojo.PageSyncTasks;
import com.changdu.seatunnel.admin.pojo.ShowTaskTables;
import com.changdu.seatunnel.admin.service.SyncConfigService;
import com.changdu.seatunnel.admin.service.SyncTaskService;
import com.changdu.seatunnel.admin.util.SyncConfigUtils;

import cn.hutool.extra.spring.SpringUtil;


@RestController
@RequestMapping("/api/task")
public class SyncTaskController {
    
    @Autowired
    private SyncTaskService syncTaskService;
    
    @Autowired
    private SyncConfigService syncConfigService;
    
    
    @GetMapping("/list")
    public PageSyncTasks list(@RequestParam(required = false, defaultValue = "") String dataCenter, 
            @RequestParam(required = false, defaultValue = "") String instance,
            @RequestParam(required = false, defaultValue = "") String database,
            @RequestParam(required = false, defaultValue = "") String table,
            @RequestParam(required = false, defaultValue = "") String jobName,
            @RequestParam(required = false, defaultValue = "") String taskType,
            @RequestParam(required = false, defaultValue = "") String stTaskId,
            @RequestParam Integer page,
            @RequestParam Integer size) {
    	
    	Page<SyncTask> pageWrap = Page.of(page, size);
    	
    	// 按任务ID搜索
    	if (StringUtils.isNotBlank(stTaskId)) {
    		return syncTaskService.getByStTaskId(pageWrap, stTaskId);
    	}
    	
    	// 按名称及任务类型进行搜索
    	if (StringUtils.isNoneBlank(jobName) || StringUtils.isNoneBlank(taskType)) {
    		return syncTaskService.listByJobNameOrSyncType(pageWrap, jobName, taskType);
    	}
    	
    	// 返回所有
    	if (StringUtils.isBlank(dataCenter) && StringUtils.isBlank(database) && StringUtils.isBlank(table)) {
    		return syncTaskService.listOrderByUpdateTime(pageWrap);
    	}
    	
    	// 按数据中心条件搜索
    	List<SyncConfig> syncConfigs = syncConfigService.selectSyncConfigs(dataCenter, instance, database, table);
    	List<Long> configIds = syncConfigs.stream().map(s -> s.getId()).collect(Collectors.toList());
    	
    	return syncTaskService.listBySyncConfigIds(configIds, pageWrap);
    }
    
    @GetMapping("/{id}")
    public SyncTask getById(@PathVariable Integer id) {
        return syncTaskService.getById(id);
    }
    
    @PostMapping
    public boolean save(@RequestBody SyncTask syncTask) {
        return syncTaskService.save(syncTask);
    }
    
    @PostMapping("/update/taskname")
    public boolean taskname(@RequestBody SyncTask syncTask) {
        return syncTaskService.updateTaskName(syncTask);
    }    
    
    @PostMapping("/update/template")
    public boolean update(@RequestBody SyncTask syncTask) {
        return syncTaskService.updateById(syncTask);
    }
    
    @DeleteMapping("/delete/{id}")
    public boolean delete(@PathVariable Integer id) {
    	return syncTaskService.deleteSeatunnelJob(id);
    }
    
    @PostMapping("/submit/{id}")
    public void submitById(@PathVariable String id, @RequestBody(required = false) JobParams jobParam) throws Exception {
        syncTaskService.submitSeatunnelJob(id, jobParam);
    }
    
    @PostMapping("/submit/batch")
    public void batchSubmitByIds(@RequestBody BatchRequest request) throws Exception {
    	if (request.isEmpty()) return;
    	
    	for (Integer taskId : request.getTaskIds()) {
    		syncTaskService.submitSeatunnelJob(String.valueOf(taskId), null);
		}
    }
    
    @GetMapping("/submitsubjob/{id}")
    public void submitSubJobById(@PathVariable Integer id) {
        syncTaskService.submitSeatunnelSubJob(id);
    }
    
    @GetMapping("/stop/{id}")
    public void stopById(@PathVariable String id, @RequestParam(defaultValue = "true", required = false) Boolean savepoint) {
        syncTaskService.stopSeatunnelJob(id, savepoint);
    }
    
    @PostMapping("/stop/batch")
    public void batchStopByIds(@RequestBody BatchRequest request) {
    	if (request.isEmpty()) return;
    	
    	for (Integer taskId : request.getTaskIds()) {
    		syncTaskService.stopSeatunnelJob(String.valueOf(taskId), request.getSavepoint());
		}
    }

    /**
     * 检查 Kafka Topic 是否存在,不存在则创建
     * @param id
     */
    @GetMapping("/checkkafkatopic/{id}")
    public void checkkafkatopic(@PathVariable Integer id) {
        syncTaskService.createSyncTaskTopic(id);
    }
    
    /**
     * 查找任务对应的表列表
     * @param id
     */
    @GetMapping("/showTables/{id}")
    public ShowTaskTables showTaskTables(@PathVariable Integer id) {
    	SyncTask task = syncTaskService.getById(id);
    	return SyncConfigUtils.toTableMappings(task);
    }
    
    /**
     * curl -i 'http://localhost:9000/api/task/showKafkaLag/1'
     * 刷新 lag
     * @param id
     */
    @GetMapping("/showKafkaLag/{id}")
    public Long showKafkaLag(@PathVariable Integer id) {
    	SyncTask task = syncTaskService.getById(id);
    	return SpringUtil.getBean(JobStateScanHandler.class).showKafkaLag(task);
    }
    
} 